package controller;

import com.alibaba.fastjson.JSONObject;
import dao.UserDao;
import model.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.BeanUtils;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserService();

    public void findAll(HttpServletRequest request, HttpServletResponse response) {
        List<User> userList = userService.findAll();
        request.setAttribute("userList", userList);
        try {
            request.getRequestDispatcher("/user/findPage").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void findPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String realName = (String) request.getParameter("realName");
        if (realName == null) {
            Object realName1 = request.getSession().getAttribute("realName");
            if (realName1!=null){
                realName=realName1.toString();
            }else {
                realName = "";
            }
        }
        request.getSession().setAttribute("realName",realName);
        Integer currPage;
        if (request.getParameter("currPage") == null) {
            currPage = 1;
        } else {
            currPage = Integer.parseInt(request.getParameter("currPage"));
        }
        PageEntity<User> pageData = userService.findPage(currPage, realName);
        request.setAttribute("pageData", pageData);
        request.setAttribute("realName", realName);
        User user = (User) request.getSession().getAttribute("user");
        System.out.println(user.getId());
        List<Userfocus> focus = userService.findFocus(user.getId());
        request.setAttribute("aFocus", focus);
        request.getRequestDispatcher("/html/user.jsp").forward(request, response);
    }

    public void findDept(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> dept = userService.findDept();
        HashMap<Object, ArrayList<Object>> maps = new HashMap<>();
        for (Map<String, Object> map : dept) {
            if (null == map.get("real_name")) {
                continue;
            }
            ArrayList list = new ArrayList();
            if (!maps.containsKey(map.get("name"))) {
                maps.put(map.get("name"), list);
            }
            list = maps.get(map.get("name"));
            list.add(map.get("real_name"));
            maps.put(map.get("name"), list);
        }
        List<Map<Object, ArrayList<Object>>> results = new ArrayList<>();
        results.add(maps);
        request.setAttribute("dept", results);
        request.getRequestDispatcher("/html/department.jsp").forward(request, response);
    }

    public void update(HttpServletRequest request, HttpServletResponse response) {
//        Object img = request.getAttribute("img");
        Object phone = request.getParameter("phone");
        Object age = request.getParameter("age");
//        Object secret = request.getParameter("secret");
        Date loginTime = new Date();
        Object name = request.getParameter("name");
        Object secret = request.getParameter("secret");
        Object[] objects = {phone, age, loginTime, secret.toString(), name.toString()};
        userService.update(objects);
        User user = (User) request.getSession().getAttribute("user");
        User upuser = userService.findByUsername(user.getUsername());
        request.getSession().setAttribute("user", upuser);
        try {
            request.getRequestDispatcher("/html/user_look.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updatePic(HttpServletRequest request, HttpServletResponse response) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
//        sfu.setFileSizeMax(1024 * 400);
        try {
            List<FileItem> items = sfu.parseRequest(request);
            String fileName = "";
            for (int i = 0; i < items.size(); i++) {
                FileItem item = items.get(i);
                if (!item.isFormField()) {
                    String name = item.getName();
                    String suffix = name.substring(name.lastIndexOf("."));
                    fileName = UUID.randomUUID().toString() + suffix;
                    File file = new File("D:/img/" + fileName);
                    if (!file.exists()) {
                        item.write(file);
                    }
                }
            }
            User user = (User) request.getSession().getAttribute("user");
            String picUrl = "http://localhost:8027/upload/" + fileName;
            user.setPic(picUrl);
            userService.updateUrl(Long.valueOf(user.getId()), picUrl);
            String res = picUrl;
            response.getWriter().write(res);
        } catch (Exception e) {
            try {
                response.getWriter().write("上传失败");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    public void userDetail(HttpServletRequest request, HttpServletResponse response) {
//        userService.UserDetail(id);
        String name = request.getParameter("name");
        User user = userService.findByUsername(name);
        request.setAttribute("userDetail", user);
        try {
            request.getRequestDispatcher("/html/user_detail.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void meetingList(HttpServletRequest request, HttpServletResponse response) {
        synchronized (userService) {
            String page = request.getParameter("currentPage");
            PageMeeting pageMeeting = new PageMeeting();
            Integer currentPage;
            if (page == null) {
                currentPage = 1;
            } else {
                currentPage = Integer.parseInt(page);
            }
            String meetingName = request.getParameter("meetingName");
            if (meetingName == null) {
                Object meetingName1 = request.getSession().getAttribute("meetingName");
                if (meetingName1!=null){
                    meetingName=meetingName1.toString();
                }else {
                    meetingName = "";
                }
            }
            request.getSession().setAttribute("meetingName",meetingName);
            int count = userService.findCount(meetingName);
            int i = count % pageMeeting.getPageSize();
            pageMeeting.setCountPage(i == 0 ? count / pageMeeting.getPageSize() : count / pageMeeting.getPageSize() + 1);
            pageMeeting.setMeetings(userService.meetingList(meetingName, (currentPage - 1) * pageMeeting.getPageSize(), pageMeeting.getPageSize()));
            pageMeeting.setCurrentPage(currentPage);
            pageMeeting.setTotalCount(i);
            request.setAttribute("meetings", pageMeeting);
            Date date = new Date();

            request.setAttribute("date", date);
            try {
                request.getRequestDispatcher("/html/meeting.jsp").forward(request, response);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void meetDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
                Integer id = Integer.valueOf(request.getParameter("id"));
                Meeting meeting = userService.meetDetail(id);
                Integer joinNum = userService.userDetail(id);
                int totalNum = meeting.getMakeUser().split(",").length;
                request.setAttribute("meetDetail", meeting);
                request.setAttribute("joinNum", joinNum);
                request.setAttribute("totalNum", totalNum);
                request.getRequestDispatcher("/html/meeting_detail.jsp").forward(request, response);
        } catch (Exception e) {
            request.getRequestDispatcher("/user/meetingList").forward(request, response);
        }
    }

    public void toFocus(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id");
            if (id != null) {
                List<User> list = userService.toFocus(Integer.valueOf(id));
                request.setAttribute("toFocus", list);
            }
            request.getRequestDispatcher("/html/my_user.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showArticle(HttpServletRequest request, HttpServletResponse response) {
        Integer currentPage;
        if (null == request.getParameter("currentPage")) {
            currentPage = 1;
        } else {
            currentPage = Integer.valueOf(request.getParameter("currentPage"));
        }
        PageEntity<Article> pageEntity = new PageEntity<>();
        pageEntity.setPageSize(4);
        Integer pageSize = pageEntity.getPageSize();
        String aName = request.getParameter("aName");
        if (null == aName) {
            Object aName1 = request.getSession().getAttribute("aName");
            if (aName1!=null){
                aName=aName1.toString();
            }else {
                aName = "";
            }
        }
        request.getSession().setAttribute("aName",aName);
        List<Article> articles = userService.showArticle(aName, (currentPage - 1) * pageSize, pageSize);
        Integer totalCount = userService.findByArticlename(aName);
        Integer totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : (totalCount / pageSize) + 1;
        pageEntity.setTotalPage(totalPage);
        pageEntity.setData(articles);
        pageEntity.setCurrPage(currentPage);
        request.setAttribute("articles", pageEntity);
        try {
            request.getRequestDispatcher("/html/article.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void collectArticle(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        if (id != null) {
            List<Article> articles = userService.collectActicle(Integer.valueOf(id));
//            List<Integer> collectCount = userService.collectCount(Integer.valueOf(id));
//            request.setAttribute("collectCount",collectCount);
            request.setAttribute("collectArticle", articles);
            try {
                request.getRequestDispatcher("/html/article_collect.jsp").forward(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void addArticle(HttpServletRequest request, HttpServletResponse response) {
        try {
            User user = (User) request.getSession().getAttribute("user");
            Integer userId = user.getId();
            String realName = user.getRealName();
            Date date = new Date();
            String title = request.getParameter("Title");
            String content = request.getParameter("Content");
            int i = 0;
            int addArticle = userService.addArticle(title, content, i, date, realName, userId);
            if (addArticle == 0) {
                response.getWriter().write("添加失败");
                return;
            }
            request.getRequestDispatcher("/user/showArticle").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addMeeting(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String mTitle = request.getParameter("mTitle");
        String sTime = request.getParameter("sTime");
        String eTime = request.getParameter("eTime");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        Date sDate = simpleDateFormat.parse(sTime);
        Date eDate = simpleDateFormat.parse(eTime);
        String mContent = request.getParameter("mContent");
        User user = (User) request.getSession().getAttribute("user");
        String deptName = user.getDeptName();
        Integer id = user.getDeptId();
        Date date = new Date();
        int i = userService.addMeeting(deptName, id, mTitle, mContent, date, sDate, eDate, 0, "[]");
        if (i == 0) {
            response.getWriter().write("添加失败");
            response.getWriter().close();
            return;
        }
        request.getRequestDispatcher("/user/meetingList").forward(request, response);
    }

    public void articleDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Article article = userService.articleDetail(Integer.valueOf(id));
        request.setAttribute("articleDetail", article);
        try {
            request.getRequestDispatcher("/html/article_detail.jsp").forward(request, response);
        } catch (Exception e) {
            request.getRequestDispatcher("/html/article_detail.jsp").forward(request, response);
        }
    }

    public void changeFocus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer userId = Integer.valueOf(request.getParameter("userId"));
        Integer id = Integer.valueOf(request.getParameter("id"));
        userService.changeFocus(userId, id);
        try {
            List<User> list = userService.toFocus(userId);
            request.setAttribute("toFocus", list);
            request.getRequestDispatcher("/html/lookCenter.jsp").forward(request, response);
        } catch (Exception e) {
            request.getRequestDispatcher("/html/lookCenter.jsp").forward(request, response);
        }
    }

    public void addFocus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Integer userId = Integer.valueOf(request.getParameter("userId"));
            Integer id = Integer.valueOf(request.getParameter("id"));
            userService.addFocus(userId, id);
            PageEntity<User> pageData = userService.findPage(1, ""); // 将PageEntity对象添加到域对象,用于前端取出数据
            request.setAttribute("pageData", pageData);
            List<Userfocus> focus = userService.findFocus(userId);
            request.setAttribute("aFocus", focus);
            request.getRequestDispatcher("/html/userCenter.jsp").forward(request, response);
        } catch (Exception e) {
            request.getRequestDispatcher("/html/userCenter.jsp").forward(request, response);
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("user");
        response.sendRedirect("index.jsp");
    }

//    public void wx_login(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        Properties prop = new Properties();
//        prop.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
//        String appid = prop.getProperty("wx.AppID");
//        String redirect_uri = prop.getProperty("wx.redirect_uri");
//        String url = "https://open.weixin.qq.com/connect/qrconnect?response_type=code" + "&appid=" + appid + "&redirect_uri=" + URLEncoder.encode(redirect_uri) + "&scope=snsapi_login";
//        response.sendRedirect(url);
//    }

    private Map<String, String> getParam(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        Map<String, String> returnMap = new HashMap<>();
        for (Map.Entry<String, String[]> entry : entries) {
            String[] values = entry.getValue();
            if (values.length > 1) {
                String val = Arrays.toString(values);
                returnMap.put(entry.getKey(), val);
            } else {
                returnMap.put(entry.getKey(), values[0]);
            }
        }
        return returnMap;
    }
}





